package com.app.songbump;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import org.apache.http.conn.util.InetAddressUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

public class SongBumpActivity extends Activity{
	
	AppPreferences appPrefs;
	String myIp;
	String myName;
	
	private AddUserReciever receiver;
	
	public class AddUserReciever extends BroadcastReceiver {
		   @Override
		    public void onReceive(Context context, Intent intent) {
			   	String response = intent.getStringExtra("response");
			   	
				int userId = -1;
				try {
					JSONObject jsonObject = new JSONObject(response);
					userId = jsonObject.getInt("id");
				} catch (JSONException e) {
					e.printStackTrace();
				}

				if(userId > 0){
					appPrefs.saveUserId(Integer.toString(userId));
					appPrefs.saveUserName(myName);
				}
				checkUser();	
		    }
	}
	
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		appPrefs = new AppPreferences(getApplicationContext());
		myIp = getMyIp();
		
		IntentFilter filter = new IntentFilter(SongBumpServer.ADD_USER_RESPONSE);
		filter.addCategory(Intent.CATEGORY_DEFAULT);
		receiver = new AddUserReciever();
		registerReceiver(receiver, filter);
		
		findViewById(R.id.saveNameButton).setOnClickListener(new View.OnClickListener() {
			
			//@Override
			public void onClick(View v) {
				Log.d("debug","button clicked!");
				EditText mUserName = (EditText) findViewById(R.id.nameTextField);
				createUserInDB(mUserName.getText().toString());
			}
		});
		checkUser();
	}
	
	public void onResume(Bundle savedInstanceState) {
		myIp = getMyIp();
		checkUser();
	}
	public void onStart(Bundle savedInstanceState) {
		myIp = getMyIp();
		checkUser();
	}
	public void onDestroy(){
		super.onDestroy();
		unregisterReceiver(receiver);
	}

	private void checkUser() {
		// TODO Auto-generated method stub
		
		String someString = appPrefs.getUserName();
		Log.v("check", someString);
		if (someString.equals("") || someString.equals(null)) {
		} // Do Nothing
		else {
			Bundle b = new Bundle();
			b.putString("ip", myIp);
			Intent intent = new Intent(getApplicationContext(),
					SongBumpTabActivity.class);
			intent.putExtras(b);
			startActivity(intent);
		}
	}
	
	private void createUserInDB(String uName){
		
		myName = uName;
		
		Intent msgIntent = new Intent(SongBumpActivity.this, SongBumpServer.class);
		msgIntent.putExtra(SongBumpServer.ACTION,SongBumpServer.ADD_USER);
		msgIntent.putExtra("name",uName);
		msgIntent.putExtra("ip",myIp);
		startService(msgIntent);
	}
	
	private String getMyIp() {
		 try {
			 String ipv4;
			 for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
	            NetworkInterface intf = en.nextElement();
	            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
	                InetAddress inetAddress = enumIpAddr.nextElement();
	                if (!inetAddress.isLoopbackAddress()&&InetAddressUtils.isIPv4Address(ipv4=inetAddress.getHostAddress())) {
	                    return ipv4;
	                }
	            }
	        }
	    } catch (SocketException ex) {
	       
	    }
	    return null;
	}
}